<template>
  <basic-container class="app-Inquiry" style="margin: 0 !important">
    <div class="top-container">
      <el-form
        :inline="true"
        :model="formInline"
        ref="formInline"
        class="demo-form-inline"
        style="display: block !important"
      >
        <el-form-item label="后台单号" style="margin-bottom: 15px !important">
          <el-input
            v-model.trim="formInline.xmbzNo"
            clearable
            size="medium"
            placeholder="后台单号"
            style="width: 163px"
          ></el-input>
        </el-form-item>
        <el-form-item label="平台单号" style="margin-bottom: 15px !important">
          <el-input
            v-model.trim="formInline.platformOrderId"
            clearable
            size="medium"
            placeholder="平台单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="城市" style="margin-bottom: 15px !important">
          <CitySelect v-model="formInline.deptIds" placeholder="城市" size="medium" @change="handleCity"
            @keydown.native="selectBlur($event)" collapse-tags multiple clearable @loadedList="handleLoadedCityList"></CitySelect>
        </el-form-item>
        <el-form-item label="收货号码" style="margin-bottom: 15px !important">
          <el-input
            v-model.trim="formInline.receiverPhone"
            onkeyup="value=value.replace(/[^\d]/g,'')"
            maxlength="11"
            clearable
            size="medium"
            placeholder="收货号码"
            style="width: 150px"
          ></el-input>
        </el-form-item>

        <el-form-item label="下单号码" style="margin-bottom: 15px !important">
          <el-input
            v-model.trim="formInline.bookerPhone"
            onkeyup="value=value.replace(/[^\d]/g,'')"
            maxlength="11"
            clearable
            size="medium"
            placeholder="下单号码"
            style="width: 150px"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="操作人"
          prop="confirmOperator"
          style="margin-bottom: 15px !important"
        >
          <el-input
            v-model.trim="formInline.confirmOperator"
            clearable
            size="medium"
            placeholder="操作人"
            style="width: 125px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="配送员"
          prop="delivery"
          style="margin-bottom: 15px !important"
        >
          <el-input
            v-model.trim="formInline.delivery"
            clearable
            size="medium"
            placeholder="配送员"
            style="width: 125px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="状态"
          style="margin-right: 0; margin-bottom: 15px !important"
        >
          <el-select
            ref="statusRef"
            v-model="formInline.status"
            clearable
            size="medium"
            placeholder="状态"
            style="width: 90px"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="item in statusList"
              :key="item.status"
              :label="item.statusName"
              :value="item.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="渠道类别"
          style="margin-bottom: 15px !important; margin-left: 10px"
        >
          <el-select
            ref="channelTypeRef"
            v-model="formInline.channelType"
            @keydown.native="keydown($event)"
            clearable
            filterable
            size="medium"
            placeholder="渠道类别"
            style="width: 140px"
          >
            <el-option
              v-for="(channelitem, channel) in channelTypellist"
              :key="channel"
              :label="channelitem.channelName"
              :value="channelitem.channelKey"
            >
              <span
                :data-id="channelitem.id"
                style="
                  display: inline-block;
                  width: 150px;
                  padding: 0 20px;
                  margin-left: -20px;
                "
                @click="getchannelTypeId($event)"
                >{{ channelitem.channelName }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" style="margin-bottom: 15px !important">
          <el-select
            ref="channelRef"
            v-model="formInline.channel"
            @keydown.native="keydown($event)"
            clearable
            filterable
            size="medium"
            placeholder="渠道"
            style="width: 155px"
          >
            <el-option
              v-for="(channelitem, channel) in channerllist"
              :key="channel"
              :label="channelitem.channelName"
              :value="channelitem.channelKey"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分仓" style="margin-bottom: 15px !important">
          <el-select
            ref="barnchWarehouseRef"
            v-model="warehouseIds"
            @keydown.native="selectBlur($event)"
            clearable
            filterable
            collapse-tags
            multiple
            size="medium"
            placeholder="分仓"
            style="width: 180px"
            @visible-change="storeSort"
          >
            <el-option
              v-for="(item, index) in barnchWarehouselist"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否跳舞" style="margin-bottom: 15px!important;">
          <DanceTypeSelect v-model="formInline.isDance" style="width: 160px;" clearable ></DanceTypeSelect>
        </el-form-item>
        <el-form-item label="商品类型" style="margin-bottom: 15px!important;">
          <CategoryTreeSelect v-model="formInline.addedServices" style="" clearable change-on-select></CategoryTreeSelect>
        </el-form-item>
        <el-form-item sytle="dispaly:flex">
          <el-select
            ref="selectRef"
            v-model="formInline.select"
            placeholder="时间"
            size="medium"
            @keydown.native="selectBlur($event)"
            style="width: 110px; margin: 0 8px"
          >
            <el-option label="配送时间" value="配送时间"></el-option>
            <el-option label="下单时间" value="下单时间"></el-option>
          </el-select>
          <el-date-picker
            v-model="timeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            size="medium"
            align="right"
          ></el-date-picker>
          <!-- <el-date-picker v-model="formInline.StartTime" type="datetime" placeholder="选择配送时间" align="right"
            :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" size="medium" style="width: 220px;"></el-date-picker>
          <span class="line" :span="1" align="center">--</span>
          <el-date-picker v-model="formInline.EndTime" type="datetime" placeholder="选择配送时间" align="right"
          :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" size="medium" style="width: 220px;"></el-date-picker>-->
        </el-form-item>
        <el-form-item style="margin-bottom: 15px !important">
          <el-button
            type="primary"
            @click="onSubmit('formInline')"
            size="medium"
            plain
            icon="el-icon-search"
            style="margin-left: 30px"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <abnormalWorkOrder class="d-ib" v-xmbz-permission="'inquiry_abnormal_notice'"></abnormalWorkOrder>
      <addedServiceNotice class="d-ib"></addedServiceNotice>
    </div>
    <div class="table-container">
      <el-table
        class="table-width"
        :data="querylist"
        header-row-class-name="table-top"
        :row-class-name="tableRowClassName"
        @sort-change="changeTableSort"
        style="width: 100%"
        border
      >
        <el-table-column
          prop="xmbzNo"
          label="后台单号"
          align="center"
          min-width="60"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.xmbzNo }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="deptName"
          label="城市"
          align="center"
        ></el-table-column>
        <el-table-column
          label="配送时间"
          :sortable="'deliveryTimeSort'"
          align="center"
          prop="deliveryStartTime"
          min-width="85"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.deliveryStartTime == ''"
              style="margin-left: 10px"
              >立即配送</span
            >
            <span
              v-if="scope.row.deliveryStartTime !== ''"
              style="display: flex; flex-direction: column"
            >
              <span>{{ scope.row.deliveryStartTime.slice(0, 10) }}</span>
              <span
                >{{ scope.row.deliveryStartTime.slice(11, 16) }}~{{
                  scope.row.deliveryEndTime.slice(11, 16)
                }}</span
              >
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="下单时间"
          :sortable="'orderTimeSort'"
          align="center"
          prop="orderTime"
          min-width="77"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.orderTime.slice(5, 16)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="收货人"
          prop="receiverName"
          align="center"
          min-width="50"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.receiverName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="平台单号" prop="platformOrderId" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.platformOrderId }}</span>
          </template>
        </el-table-column>-->
        <el-table-column
          label="收货号码"
          prop="receiverPhone"
          align="center"
          min-width="60"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.receiverPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="商品明细"
          prop="receiverPhone"
          align="center"
          min-width="180"
        >
          <template slot-scope="scope">
            <p v-for="(detail, index) in scope.row.orderDetailVOS" :key="index">
              <span>{{detail.goodsName}}</span>
              <span style="color: #f56c6c"
                >({{ detail.goodsSpecs }}，{{ detail.num }})</span
              >
            </p> </template
          ><strong></strong>
        </el-table-column>
        <el-table-column
          label="配送地址"
          prop="receiverAddress"
          align="center"
          min-width="150px"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              scope.row.receiverAddress
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="渠道"
          prop="channelName"
          align="center"
          min-width="53px"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.channelName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="订单状态"
          prop="statusName"
          align="center"
          min-width="55"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.statusName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="异常反馈"
          prop="abnormalContent"
          align="center"
          min-width="55"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px; color: red">{{
              scope.row.abnormalContent
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="customerServiceNotes"
          align="center"
          min-width="80"
        >
          <template slot="header" slot-scope="scope">
            <div class="lh-20">客服备注</div>
            <div class="lh-20 c-red">仅客服使用</div>
          </template>
          <template slot-scope="scope">
            <span style="margin-left: 10px; color: red">{{
              scope.row.customerServiceNotes
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作人"
          prop="confirmOperator"
          align="center"
          min-width="43"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px; color: red">{{
              scope.row.confirmOperator
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="配送员"
          prop="delivery"
          align="center"
          min-width="45"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px; color: red">{{
              scope.row.delivery
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="分仓"
          prop="branchWarehouse"
          align="center"
          min-width="35"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px; color: red">{{
              scope.row.branchWarehouse
            }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="是否跳舞" prop="isDance">
          <template slot-scope="scope">
            <span>{{ danceLabelMap[scope.row.isDance] || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="responsibleDepartmentErrorText" label="部门失误类型" align="center" min-width="100">
          <template slot-scope='scope'>
            <span class="el-button--text cs-p" @click="viewResponsibleDetail(scope.row)">
              {{scope.row.responsibleDepartmentErrorText}}
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" prop="transportDisposeContent" label="咨询快乐工单结果" align="center"></el-table-column>
        <el-table-column
          fixed="right"
          label="说明"
          align="center"
          min-width="130px"
        >
          <template slot-scope="scope">
            <el-tag type="danger" size="mini" class="d-b mb-5" v-if="scope.row.replaceCake == 1">蛋糕原料缺失</el-tag>
            <el-tag type="info" size="mini" class="d-b mb-5" v-if="scope.row.refundNotReturnName === '退款不退货'">退款不退货</el-tag>
            <el-tag type="warning" size="mini" class="d-b mb-5" v-if="scope.row.refundMark == '平台退款中'">平台退款中</el-tag>
            <el-tag type="info" size="mini" class="d-b mb-5" v-for="tag in JSON.parse(scope.row.orderTags === '' ? '[]' : scope.row.orderTags)">{{ tag }}</el-tag>

            <el-tag type="warning" size="mini" class="d-b mb-5 tag-c-1abc9c" v-if="scope.row.staffForward">{{ scope.row.staffForward }}</el-tag>
            <el-tag type="warning" size="mini" class="d-b mb-5 tag-c-3498db" v-if="scope.row.tyingRefundNotReturn">{{ scope.row.tyingRefundNotReturn }}</el-tag>
            <el-tag type="warning" size="mini" class="d-b mb-5 tag-c-9b59b6" v-if="scope.row.customChange">客户自助修改了信息</el-tag>
            <el-tag type="warning" size="mini" class="d-b mb-5 tag-c-e67e22" v-if="scope.row.cancelRefundMark">{{ scope.row.cancelRefundMark }}</el-tag>
            <el-tag type="warning" size="mini" class="d-b mb-5 tag-c-c586c0" v-if="scope.row.handleStateName">{{ scope.row.handleStateName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="addedServiceVO" label="增值服务信息" fixed="right" min-width="100">
          <template slot-scope='scope'>
            <template v-if="scope.row.addedServiceVO && scope.row.addedServiceVO.length">
              <div class="addservice-item" v-for="(item, i) in scope.row.addedServiceVO" :key="i">
                <div class="fz-12">{{ item.typeName }}</div>
                <div class="fz-12 lh-16 c-999" v-if="item.passValue">
                  <el-tag class="mr-5" :type="item.pass == '1' ? 'success' : 'danger'" size="mini">{{ item.pass == '1' ? '满足' : '不满足' }}</el-tag>
                  {{ item.passValue }}
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="left" min-width="110">
          <template slot-scope="scope">
            <div class="operate-btns">
              <i v-if="permissionList.inquiry_edit" class="btn-item el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</i>
              <i v-if="permissionList.inquiry_journal" class="btn-item el-icon-mobile" @click="handleOrderLog(scope.row)">日志</i>
              <i v-if="permissionList.inquiry_view" class="btn-item el-icon-view" @click="handleViewLog(scope.$index, scope.row)">查看</i>
              <!-- <i v-if="permissionList.inquiry_shortmessage" class="btn-item" @click="handleSMS(scope.$index, scope.row)">短信记录</i> -->
              <i v-if="permissionList.inquiry_SMSsend" class="btn-item" @click="handleSMSsend(scope.$index, scope.row)">短信发送</i>
              <i v-if="permissionList.inquiry_replenish" class="btn-item" @click="handleReplenish(scope.$index, scope.row)">异常补单</i>
              <!-- <i class="btn-item" @click="handleConsultHappy(scope.row)">咨询快乐工单</i> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="formInline.page"
        :limit.sync="formInline.size"
        @pagination="getList"
      />
    </div>
    <el-dialog
      title="发送短信"
      :visible.sync="SMSsendviewFlag"
      :before-close="handleSMSClose"
      width="45%"
    >
      <el-form
        :model="SMSruleForm"
        status-icon
        :rules="SMSrules"
        ref="SMSruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="width: 90%"
      >
        <el-form-item label="发送给" prop="phoneNumbers">
          <el-input
            v-model.number="SMSruleForm.phoneNumbers"
            placeholder="请输入手机号码"
            clearable
            maxlength="11"
            @keydown.native="temNselectBlur($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="模板类型" prop="templateNames">
          <el-select
            id="InauirytempName"
            v-model="SMSruleForm.templateNames"
            filterable
            placeholder="请选择短信模板"
            @change="getSmsTemplatePageInfo()"
            clearable
            @keydown.native="temNselectBlur($event)"
            style="width: 100%"
          >
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.templateName"
              :value="item.templateContent"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信内容" prop="content">
          <el-input
            :required="false"
            type="textarea"
            v-model="SMSruleForm.content"
            placeholder="短信内容"
            :readonly="true"
            :autosize="
              SMSruleForm.content == '' ? { minRows: 2, maxRows: 4 } : ''
            "
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="SMSresetForm('SMSruleForm')">取消</el-button>
          <el-button type="primary" @click="SMSsubmitForm('SMSruleForm')"
            >确认</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 异常补单 -->
    <el-dialog
      destroy-on-close
      title="异常补单"
      :visible.sync="replenishFormVisible"
      width="400"
    >
      <replenish
        :replenishObject="replenishObject"
        @replenishClose="replenishClose"
        v-if="replenishFormVisible"
      ></replenish>
    </el-dialog>

    <complaintDetailDialog ref="complaintDetailDialog"></complaintDetailDialog>
    <addConsultHappyDialog ref="addConsultHappyDialog"></addConsultHappyDialog>
    <orderLogDialog ref="orderLogDialog"></orderLogDialog>
  </basic-container>
</template>

<script>
import {
  orderList, // 查询
  statusList, // 订单状态
  forceUnlock, // 强制解锁
  startUpdate, //开始修改
  getWarehouseListCityIds,
  getOrderOperateLog, // 订单日志
  add0rderOperateLog, // 添加订单操作日志
  unlockOrder, //解锁
} from "@/api/pending";
import {
  SmsTemplateNameAndContent, // 短信模板
  sendInquirySms, // 短信发送
  getDefaultSmsTemplate, // 返回订单要发的短信内容
} from "@/api/customer";
import {
  citySelect, // 城市
  getOrderChannelList, // 渠道
  getOrderChannelTypeList, // 渠道类别列表
} from "@/api/createOrder";
import { getAnomalyReplacementOrder } from "@/api/orderReplenish";
import Pagination from "@/components/Pagination";
import replenish from "@/components/order-replenish/replenishInfo";
import { mapGetters } from "vuex"; // 分页
import { danceLabelMap } from '@/const'
import abnormalWorkOrder from './abnormalWorkOrder'
import addedServiceNotice from './addedServiceNotice'
import complaintDetailDialog from '@/components/order/complaintDetailDialog'
import { last } from 'lodash'
import addConsultHappyDialog from '@/views/workOrder/consultHappy/addDialog'
import orderLogDialog from '@/components/dialog/orderLogDialog'

const windowMap = {}

export default {
  components: {
    Pagination,
    replenish,
    abnormalWorkOrder,
    addedServiceNotice,
    complaintDetailDialog,
    addConsultHappyDialog,
    orderLogDialog,
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      setTimeout(() => {
        if (value !== "") {
          if (!Number.isInteger(value)) {
            callback(new Error("请输入数字值"));
          } else {
            if (value.toString().length !== 11) {
              callback(new Error("号码长度应为11位"));
            } else {
              callback();
            }
          }
        }
      }, 1000);
    };
    return {
      barnchWarehouselist: [],
      total: 0,
      formInline: {
        bookerPhone: "", //下单号码
        deptIds: [], // 城市id
        xmbzNo: "", // 后台单号
        platformOrderId: "", // 平台单号
        status: "",
        channelType: "", // 渠道类别
        channel: "", // 渠道
        select: "配送时间",
        StartTime: "",
        EndTime: "",
        receiverPhone: "", // 收货号码
        deliveryStartTime: "", // 配送开始时间
        deliveryEndTime: "", // 配送结束时间
        orderTimeStart: "", // 下单开始时间
        orderTimeEnd: "", // 下单结束时间
        orderTimeSort: 0, // 下单时间排序
        deliveryTimeSort: 0, // 配送时间排序
        delivery: "", //配送员
        confirmOperator: "", //操作人
        isDance: undefined,
        page: 1,
        limit: 10,
        size: 10,
      },
      warehouseIds: [],
      replenishFormVisible: false,
      replenishObject: {
        replenishId: "",
        replenishXmbzNo: "",
        replenishDeptId: "",
        replenishDeptName: "",
      },
      channerllist: "", //渠道
      querylist: [],
      Loading: true,
      statusList: "", // 状态
      pickerOptions: {
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
        disabledDate: (time) => {
          if (this.pickerMinDate) {
            const day1 = 31 * 24 * 3600 * 1000;
            let maxTime = this.pickerMinDate + day1;
            let minTime = this.pickerMinDate - day1;
            return time.getTime() > maxTime || time.getTime() < minTime;
          }
        },
      },
      channelTypellist: "", // 渠道类别列表
      getChannelList: {
        // 渠道列表
        parentId: "",
      },
      startUpdateList: {
        //开始修改列表
        orderId: 1,
      },
      timeValue: [
        this.dayjs().format('YYYY-MM-DD') + ' 00:00',
        this.dayjs().format('YYYY-MM-DD') + ' 23:59',
      ], // 查询时间值
      SMSruleForm: {
        // 短信发送
        phoneNumbers: "",
        templateName: "", // 短信模板
        templateNames: "",
        content: "",
      },
      SMSrules: {
        phoneNumbers: [
          { required: true, validator: checkPhone, trigger: "change" },
        ],
        templateNames: [
          { required: true, message: "请选择短信模板", trigger: "change" },
        ],
      },
      SMSsendviewFlag: false, // 短信发送弹框
      templateList: [], //短信模板
      danceLabelMap,
    };
  },
  created() {
    window.addEventListener("keydown", this.keyupEnter);
    window.unlockOrder = (orderId) => {
      unlockOrder({ orderId: orderId });
      this.closeEditWindow(orderId)
    };
  },
  watch: {
    "SMSruleForm.templateNames"() {
      setTimeout(() => {
        if (document.getElementById("InauirytempName").value == "小熊猫电话")
          this.getdefaulttem();
      }, 500);
    },
  },
  mounted() {
    // 渠道类别列表
    getOrderChannelTypeList().then((res) => {
      this.channelTypellist = res.data.data;
    });
    // 状态列表接口
    statusList().then((res) => {
      this.statusList = res.data.data;
    });
    this.getList();
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        inquiry_edit: this.vaildData(this.permission.inquiry_edit, false),
        inquiry_journal: this.vaildData(this.permission.inquiry_journal, false),
        inquiry_view: this.vaildData(this.permission.inquiry_view, false),
        inquiry_shortmessage: this.vaildData(
          this.permission.inquiry_shortmessage,
          false
        ),
        inquiry_SMSsend: this.vaildData(this.permission.inquiry_SMSsend, false),
        inquiry_replenish: this.vaildData(
          this.permission.inquiry_replenish,
          false
        ),
      };
    },
  },
  methods: {
    // 分仓选中项排名靠前
    storeSort(isShow) {
      if (isShow) {
        this.warehouseIds.forEach((ids) => {
          this.barnchWarehouselist.forEach((item, index) => {
            if (item.id == ids) {
              this.barnchWarehouselist.splice(index, 1);
              this.barnchWarehouselist.unshift(item);
            }
          });
        });
      }
    },
    // 获取城市
    handleCity(data) {
      this.getWarehouseList();
    },
    handleLoadedCityList(cityList) {
      if(cityList && cityList.length == 1) {
        this.formInline.deptIds = [cityList[0].id]
      }
      this.getWarehouseList()
    },
    getWarehouseList() {
      const params = {
        cityIds: this.formInline.deptIds && this.formInline.deptIds.join(',')
      }
      getWarehouseListCityIds(params).then(
        (res) => {
          this.barnchWarehouselist = res.data.data;
        }
      );
    },

    handleOrderLog(item) {
      this.$refs.orderLogDialog.show({orderId: item.id})
    },
    onSubmit() {
      this.formInline.page = 1;
      this.getList();
    },
    // 点击编辑，打开详情
    handleEdit(index, row) {
      var authority = JSON.parse(window.localStorage.getItem("saber-userInfo"))
        .content.authority;

      const { href } = this.$router.resolve({
        path: `/orderdetail`,
        query: {
          id: row.id,
          cityId: row.deptId,
          deptName: row.deptName,
          kind: "Inquiry-order",
        },
      });
      this.startUpdateList.orderId = row.id;
      let orderId = row.id;
      startUpdate(this.startUpdateList)
        .then((res) => {
          if (res.data.success == true) {
            this.add0rderInquiry(orderId, 98); // 解锁日志
            this.openEditWindow(orderId, href)
          } else if (res.data.success == false) {
            const hasUnlockPermission = this.permission['inquiry_unlock']
            if (hasUnlockPermission) {
              this.$confirm("是否需要强制解锁此订单?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  forceUnlock(this.startUpdateList).then((res) => {
                    if (res.data.code == 200) {
                      this.add0rderInquiry(orderId, 100); // 解锁日志
                      this.$message({
                        type: "success",
                        message: "解锁成功!",
                      });
                      this.openEditWindow(orderId, href)
                    }
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消解锁成功",
                  });
                });
            } else {
              this.$message({
                type: "warning",
                message: "订单已被锁定！",
              });
            }
          }
        })
        .catch((error) => {
          console.log("333", error);
        });
    },
    openEditWindow(orderId, href) {
      if (windowMap[orderId]) {
        windowMap[orderId].close()
        windowMap[orderId] = null
      }
      setTimeout(() => {
        windowMap[orderId] = window.open(href, orderId)
      }, 100)
      
    },
    closeEditWindow(orderId) {
      if (windowMap[orderId]) {
        windowMap[orderId].close()
        windowMap[orderId] = null
      }
    },
    // 异常补单
    handleReplenish(index, row) {
      const params = {
        originOrderId: row.id,
      };
      getAnomalyReplacementOrder(params)
        .then((res) => {
          if (res.code === 400) {
            this.$message({
              type: "warning",
              message: res.data.message,
            });
          }
          if (res.data.data.status === "1") {
            let preUrl = this.$router.resolve({
              path: "/replenishCopyOrder",
              query: {
                id: row.id,
                xmbzNo: row.xmbzNo,
                cityId: row.deptId,
                deptName: row.deptName,
                pageType: 'replenishCopy'
              },
            });
            window.open(preUrl.href, "_blank");
          }
          if (res.data.data.status === "0") {
            this.replenishFormVisible = true;
            this.replenishObject.replenishId = row.id;
            this.replenishObject.replenishXmbzNo = row.xmbzNo;
            this.replenishObject.replenishDeptId = row.deptId;
            this.replenishObject.replenishDeptName = row.deptName;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 咨询快乐
    handleConsultHappy(orderData) {
      this.$refs.addConsultHappyDialog.show({ type: 'add', orderData })
    },
    dealData(authority) {
      const newArr = [];
      authority.forEach((item) => {
        newArr.push({
          checked: true,
          value: item,
        });
      });
      return newArr;
    },
    // 查询列表
    getList() {
      const errorMsg = this.validateParams()
      if (errorMsg) {
        this.$message.warning(errorMsg);
        return
      }
      this.Loading = true;
      const params = this.getParams()
      orderList(params).then((res) => {
        this.total = res.data.data.total;
        this.querylist = res.data.data.rows;
        setTimeout(() => {
          this.Loading = false;
        }, 0.5 * 1000);
      });
    },
    validateParams() {
      if (!this.checkNeedOtherParams()) {
        return `查询时，必须包含如下一个条件，【后台单号】【平台单号】【收货号码】【下单号码】【操作人】【配送员】`
      }
      if (!this.checkNeedTime()) {
        return "请输入搜索时间，且跨度不能超过31天"
      }
      if (!this.isgreaterThan()) {
        return "时间间隔不可超过31天"
      }
    },
    // 带时间查询时，需要包含一个其他条件
    checkNeedOtherParams() {
      if (
        !this.permission.inquiry_all_data &&
        (this.timeValue && this.timeValue.length) &&
        (!this.formInline.xmbzNo &&
          !this.formInline.platformOrderId &&
          !this.formInline.receiverPhone &&
          !this.formInline.bookerPhone &&
          !this.formInline.confirmOperator &&
          !this.formInline.delivery)
      ) {
        return false
      }
      return true
    },
    // 验证需要选择时间
    checkNeedTime() {
      if (
        (!this.formInline.xmbzNo &&
          !this.formInline.platformOrderId &&
          !this.formInline.receiverPhone) &&
        (this.formInline.confirmOperator !== "" ||
          this.formInline.delivery !== "" ||
          this.formInline.status !== "" ||
          this.formInline.channelType !== "" ||
          this.formInline.channel !== "" ||
          this.warehouseIds.length > 0) &&
        !(this.timeValue && this.timeValue.length)
      ) {
        return false
      }
      return true
    },
    getParams() {
      const f = this.formInline
      const params = {
        ...this.formInline,
        deptIds: this.formInline.deptIds && this.formInline.deptIds.filter(item => item).join(','),
        distinguishingFields: this.formInline.select === "配送时间" ? '1' : '2',
        warehouseIds: this.warehouseIds.length > 0 ? this.warehouseIds.join(",") : "",
        addedServices: last(f.addedServices)
      }
      if (this.timeValue && this.timeValue.length &&
        !this.formInline.xmbzNo &&
        !this.formInline.platformOrderId &&
        !this.formInline.receiverPhone) {
          if (this.formInline.select === "下单时间") {
            params.orderTimeStart = this.timeValue[0] + ":00";
            params.orderTimeEnd = this.timeValue[1] + ":00";
          } else if (this.formInline.select === "配送时间") {
            params.deliveryStartTime = this.timeValue[0] + ":00";
            params.deliveryEndTime = this.timeValue[1] + ":59";
          }
      }
      return params
    },
    // 紧急单颜色变化
    tableRowClassName({ row }) {
      // console.log(row.getHour,row.id,'row')
      const needWarning = row.orderDetailVOS && row.orderDetailVOS.some(item => item.goodsName.includes('不含跳舞一小时送达'))
      if (row.getHour === false || needWarning) {
        // console.log('false')
        return "warning-row";
      }
      return "";
    },
    // 计算时间差
    getHour(endTime) {
      let nowYear = new Date().getFullYear();
      let nowMonth =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let nowDate =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let nowHours =
        new Date().getHours() < 10
          ? "0" + new Date().getHours()
          : new Date().getHours();
      let nowMinutes =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let nowTime =
        nowYear +
        "-" +
        nowMonth +
        "-" +
        nowDate +
        " " +
        nowHours +
        ":" +
        nowMinutes;
      let s1 = new Date(endTime.replace(/-/g, "/"));
      let s2 = new Date(nowTime.replace(/-/g, "/"));
      let ms = Math.abs(s1.getTime() - s2.getTime());
      let getHour = ms / 1000 / 60 / 60;
      return getHour;
    },
    // 选择渠道类型
    getchannelTypeId(e) {
      // 渠道列表接口
      this.getChannelList.parentId = e.currentTarget.dataset.id;
      // 渠道列表接口
      getOrderChannelList(this.getChannelList).then((res) => {
        let result = res.data.data;
        result.forEach((item) => {
          this.channerllist = result;
          if (this.formInline.channel !== undefined) {
            if (item.channelKey == this.formInline.channel) {
              this.channerllist = result;
            } else {
              this.channerllist = result;
              this.formInline.channel = "";
            }
          }
        });
      });
    },
    // 排序
    changeTableSort(column) {
      if (column.prop === "orderTime" && column.order === "ascending") {
        this.formInline.orderTimeSort = 1;
        this.formInline.deliveryTimeSort = "";
        this.getList();
      } else if (column.prop === "orderTime" && column.order === "descending") {
        this.formInline.orderTimeSort = 2;
        this.formInline.deliveryTimeSort = "";
        this.getList();
      } else if (
        column.prop === "deliveryStartTime" &&
        column.order === "ascending"
      ) {
        this.formInline.deliveryTimeSort = 1;
        this.formInline.orderTimeSort = "";
        this.getList();
      } else if (
        column.prop === "deliveryStartTime" &&
        column.order === "descending"
      ) {
        this.formInline.deliveryTimeSort = 2;
        this.formInline.orderTimeSort = "";
        this.getList();
      }
    },
    // 查看订单
    handleViewLog(index, row) {
      let newUrl = this.$router.resolve({
        path: "/viewOrdInfor",
        query: {
          id: row.id,
        },
      });
      let type = 101;
      let orderId = row.id;
      this.add0rderInquiry(orderId, type);
      window.open(newUrl.href, "_blank");
    },
    // 判断是否大于31天
    isgreaterThan() {
      if (this.timeValue && this.timeValue.length) {
        var data1 = Date.parse(this.timeValue[0].replace(/-/g, "/"));
        var data2 = Date.parse(this.timeValue[1].replace(/-/g, "/"));
        var datadiff = data2 - data1;
        var time = 31 * 24 * 60 * 60 * 1000;
        if (datadiff > time) {
          return false;
        }
      }
      return true;
    },
    // 查询短信记录
    handleSMS(index, row) {
      let newUrl = this.$router.resolve({
        path: "/SMSrecord",
        query: {
          id: row.id,
          cityId: row.deptId,
          deptName: row.deptName,
          kind: "SMS-orders",
          // paperName: this.paperName,
        },
      });
      window.open(newUrl.href, "_blank");
    },
    // 添加订单操作日志
    add0rderInquiry(orderId, type) {
      let queryOrder = {
        orderId,
        type,
        orderType: 1,
        workType: 0,
      };
      add0rderOperateLog(queryOrder).then((res) => {
        console.log("res", res.data.code);
      });
    },
    // 静止输入空格
    keydown(event) {
      if (event.keyCode == 32) {
        event.returnValue = false;
      }
      if (event.keyCode == 13) {
        this.$refs["channelTypeRef"].blur();
        this.$refs["channelRef"].blur();
        event.returnValue = false;
      }
    },
    // 回车事件
    keyupEnter() {
      // const that = this;
      if (window.event.keyCode == 13) {
        this.onSubmit();
      }
    },
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs["deptRef"].blur();
        this.$refs["statusRef"].blur();
        this.$refs["selectRef"].blur();
        this.$refs["barnchWarehouseRef"].blur();
        e.returnValue = false;
      }
    },
    handleSMSClose(action, done) {
      this.$refs.SMSruleForm.resetFields();
      this.SMSsendviewFlag = false;
    },
    // 打开短信发送弹窗
    handleSMSsend(index, row) {
      this.getSmsTemplatePageInfo(); //
      this.orderId = row.id;
      this.getdefaulttem();
      this.SMSsendviewFlag = true;
    },
    // 获取默认模板
    getdefaulttem() {
      getDefaultSmsTemplate({ orderId: this.orderId }).then((res) => {
        if (String(Number(res.data.data.phoneNumbers)) !== "NaN")
          this.SMSruleForm.phoneNumbers = Number(res.data.data.phoneNumbers);
        this.SMSruleForm.templateNames = res.data.data.templateName;
        this.SMSruleForm.content = res.data.data.content;
        this.SMSruleForm.templateName = res.data.data.templateName;
        this.SMSruleForm.orderId = res.data.data.orderId;
      });
    },
    // 短信发送
    SMSsubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.SMSruleForm.templateName =
            document.getElementById("InauirytempName").value;
          sendInquirySms(this.SMSruleForm)
            .then((res) => {
              if (res.data.code == 200) {
                this.$message.success("发送成功");
                this.$refs[formName].resetFields();
                this.SMSsendviewFlag = false;
                // this.getList();
              }
            })
            .catch((error) => {
              console.log(error);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 短信发送取消
    SMSresetForm(formName) {
      this.$refs[formName].resetFields();
      this.SMSsendviewFlag = false;
    },
    getSmsTemplatePageInfo() {
      SmsTemplateNameAndContent({ type: 99 }).then((res) => {
        this.templateList = res.data.data;
      });
      this.SMSruleForm.content = this.SMSruleForm.templateNames;
    },
    temNselectBlur(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    viewResponsibleDetail(order) {
      this.$refs.complaintDetailDialog.show(order)
    },
    replenishClose() {
      this.replenishFormVisible = false
    }
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyupEnter);
  },
  activated() {
    this.roleName = JSON.parse(
      window.localStorage.getItem("saber-userInfo")
    ).content.authority;
    window.addEventListener("keydown", this.keyupEnter);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  deactivated() {
    window.removeEventListener("keydown", this.keyupEnter);
  },
};
</script>

<style lang="scss">
.red {
  color: #ff0000;
}
.app-Inquiry {
  padding-right: 5px;
  .top-container {
    padding: 20px 10px 10px 20px;

    .el-form {
      .el-form-item {
        .line {
          margin: 0 3px;
          color: #8c919c;
        }
      }
    }

    .demo-form-inline {
      display: inline-block;
    }

    .el-form-item {
      margin-bottom: 20px !important;
    }
  }

  .table-container {
    padding-left: 20px;

    .table-top {
      font-size: 13px;
      th {
        padding: 5px 2px;
        .cell {
          padding: 0;
        }
      }
    }

    .el-table {
      .operate-btns {
        .btn-item {
          color: #409eff;
          padding: 4px;
          margin-left: 0;
          display: block;
          font-style: normal;
          line-height: 1;
          font-weight: 600;
          cursor: pointer;
          &:hover {
            color: #66b1ff;
          }
        }
      }
    }

    .el-table__row {
      td {
        padding: 5px 2px;
        font-size: 13px;
        font-weight: 600;
        .cell {
          padding: 0;
          span {
            margin-left: 0;
          }
        }
      }
    }

    .active {
      color: #409eff;
      font-size: 13px;
      font-weight: 600;
    }

    .buttoncolor {
      color: #000;
      font-size: 13px;
      font-weight: 600;
    }

    .warning-row {
      background: oldlace;
      color: #e6a23c;
    }
  }
}
.el-date-range-picker .el-picker-panel__footer .el-button--text span {
  display: none;
}
.table-width {
  .el-table__fixed {
    .el-table__fixed-body-wrapper {
      .el-table__body {
        .el-table__row {
          td {
            .cell {
              span {
                margin-left: 0 !important;
              }
            }
          }
        }
      }
    }
  }
}
.addservice-item {
  border-radius: 4px;
  padding: 4px;
  margin-bottom: 12px;
  background-color: #ecf5ff;
}
</style>
